// pages/receiptNotice/receiptNotice.js
var bxt = require('../../utils/bxt.js')
var upyun = require('../../utils/upyun.js')
var userModel = require('../../models/user.js')
var noticeModel = require('../../models/notice.js')
let createReceiptOperation = require('../../operation/createReceiptOperation.js')
let updateReceiptOperation = require('../../operation/updateReceiptOperation.js')
var options // 保存上个界面传来的数据:创建模式：学生的sid；修改模式：receiptSid

var uploadedImageIndex = 0 // 当前上传图片序号
var formData = null; // 表单数据

Page({

  /**
   * 页面的初始数据
   */
  data: {
    notice:{},
    receipt:{},
    currentReceiptRequirement:{},
    images: [],  // 界面中显示的图片数据
    imageSize: 0,  //  界面中显示的图片数量
    disabled: false, // 确定按钮可用/不可用控制
    loading: false, // 通信加载提示
  },

  /**
   * 生命周期函数--监听页面加载
   * params options: {'notice':{}}
   */
  onLoad: function (options) {
    this.options = options
    this.setData({
      notice:getApp().globalData.param.notice,
      currentReceiptRequirement: noticeModel.getReceiptRequirement(getApp().globalData.param.notice.receiptRequirement)
    })


    if (noticeModel.RECEIPT_REQUIREMENT[2].value == this.data.notice.receiptRequirement) {     // 图片模式
      if (getApp().globalData.param.images) {
        this.setData({
          images: getApp().globalData.param.images,
          imageSize: getApp().globalData.param.images.length
        })
      }
    } else if (noticeModel.RECEIPT_REQUIREMENT[3].value == this.data.notice.receiptRequirement) {     // 视频模式
      if (getApp().globalData.param.video) {
        let tmpReceipt = this.data.receipt
        if (null == tmpReceipt.video) {
          tmpReceipt.video = {}
        }
        tmpReceipt.video.url = getApp().globalData.param.video
        this.setData({
          receipt: tmpReceipt
        })
      }      
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  onNext:function(event) {
    formData = event.detail.value;
    getApp().createFormId(event.detail.formId)
    if (noticeModel.RECEIPT_REQUIREMENT[2].value == this.data.notice.receiptRequirement) { // 检查是不是图片回执
      if (this.checkUploadImages()) { // 检查有没有要上传的图片
        this.uploadImage();
      } else {
        // 没有图片直接上传回执
        if (0 == this.data.images.length) {
          wx.showModal({
            title: '提示',
            content: '请选择图片',
            showCancel: false
          })
        }else {
          this.uploadReceipt();
        }
      }
    } else if (noticeModel.RECEIPT_REQUIREMENT[3].value == this.data.notice.receiptRequirement) { // 检查是不是视频回执
      if (this.checkUploadVideo()) {  // 检查有没有要上传的视频
        this.uploadVideo();
      }else {
        // 没有图片直接上传回执
        if ('' == this.data.receipt.video || null == this.data.receipt.video) {
          wx.showModal({
            title: '提示',
            content: '请选择视频',
            showCancel: false
          })
        }else {
          this.uploadReceipt();
        }        
      }
    } else {
      if (0 == formData.content.length) {
        wx.showModal({
          title: '提示',
          content: '请填写签收内容',
          showCancel: false
        })
      }else {
        this.uploadReceipt();
      }      
    }
  },

  /**
   * 点击图片预览事件处理函数
   */
  previewImage: function (event) {
    wx.previewImage({
      current: event.currentTarget.dataset.path,
      urls: this.data.images
    })
  },

  /**
   * 点击删除图片事件处理函数
   */
  onDelImage: function (event) {
    var tmpfiles = this.data.images;
    tmpfiles.splice(event.currentTarget.id, 1);
    this.setData({
      images: tmpfiles,
      imageSize: tmpfiles.length
    })
  },

  /**
   * 点击选择图片事件处理函数
   */
  chooseImage: function () {
    var that = this, length = 0, tmpfiles;
    if (that.data.images) {
      length = that.data.images.length
    }
    var size = 9 - length;
    wx.chooseImage({
      count: size,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        tmpfiles = that.data.images.concat(res.tempFilePaths)
        that.setData({
          images: tmpfiles,
          imageSize: tmpfiles.length
        })
      }
    })
  },

  /**
   * 点击选择视频事件处理函数
   */
  chooseVideo:function() {
    var that = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],      
      maxDuration: 60,
      success: function(res) {
        console.log(res)
        var tmpReceipt = that.data.receipt
        if (null == tmpReceipt.video) {
          tmpReceipt.video = {}
        }
        tmpReceipt.video.url = res.tempFilePath
        that.setData({
          receipt:tmpReceipt
        })
      }
    })
  },

  /**
   * 点击播放视频事件处理函数
   */
  onPlayVideo:function(e) {
    wx.navigateTo({
      url: '../playVideo/playVideo?src=' + this.data.receipt.video.url,
    })
  },

  /**
   * 点击删除视频事件处理函数
   */
  onDelVideo:function() {
    var tmpReceipt = this.data.receipt
    tmpReceipt.video = null
    this.setData({
      receipt: tmpReceipt
    })
  },

  /**
   * 获取需要上传服务器的视频
   * return boolean
   */
  checkUploadVideo: function () {
    var result = false

    if (null != this.data.receipt.video && this.data.receipt.video.url.indexOf('://tmp') > 0) { // 包含http://tmp/ 字符串认为是本地新选择的文件
        result = true
      }

    return result
  },

  /**
   * 上传图片到又拍云
   */
  uploadImage: function () {
    var that = this
    if (uploadedImageIndex + 1 <= this.data.images.length) {
      this.setButtonLoading(true)

      if (0 > this.data.images[uploadedImageIndex].indexOf('://tmp')) {
        uploadedImageIndex++
        this.uploadImage()
        return
      }
    
      upyun.uploadImage(this.data.images[uploadedImageIndex], bxt.UP_YUN_IMAGE_PATH,
        function (filePath, videoThumbnail) {
          let images = that.data.images
          images[uploadedImageIndex] = filePath
          that.setData({
            images: images
          })
          uploadedImageIndex++
          that.uploadImage()
        },
        function (fail) {
          wx.showToast({
            title: fail,
            icon:'none'
          })
          that.setButtonLoading(false)
        })

    } else {
      // 图片上传完成处理流程
      that.uploadReceipt();
    }
  },

  /**
   * 上传视频到又拍云
   */
  uploadVideo: function () {
    var that = this
    this.setButtonLoading(true)

    upyun.uploadImage(this.data.receipt.video.url, bxt.UP_YUN_VIDEO_PATH,
      function (filePath, videoThumbnail) {
        let receipt = that.data.receipt
        
        if (null == receipt.video) {
          receipt.video = {}
        }
        
        receipt.video.url = filePath
        receipt.video.thumbnail = videoThumbnail
        that.setData({
          receipt:receipt
        })
        that.uploadReceipt();
      },
      function (fail) {
        wx.showToast({
          title: fail,
        })
        that.setButtonLoading(false)
      })
  },

  /** 检查有没有要上传的图片 */
  checkUploadImages: function () {
    var result = false
    
    for (var index = 0; index < this.data.images.length; index++) {
      if (this.data.images[index].indexOf('://tmp') > 0) { // 包含http://tmp/ 字符串认为是本地新选择的文件
        result = true
        break
      }
    }
    
    return result
  },

  /**
   * 创建\修改回执
   */
  uploadReceipt: function () {
    var that = this
    var params = new Object()
    if (this.options.studentSid) {
      params.studentSid = this.options.studentSid
      params.noticeSid = this.data.notice.sid
    }
   
    if (0 < formData.content.length) {
      params.content = formData.content;
    }else {
      params.content = ''
    }
    if (this.data.images) {
      params.images = this.data.images.join('|');
    } else {
      params.images = ''
    }
    if (this.data.receipt.video) {
      params.video = this.data.receipt.video.url
      params.thumbnail = this.data.receipt.video.thumbnail
    }

    if (this.options.studentSid) {
      createReceiptOperation.createReceipt(this, params)
        .then(res => {
          that.back()
        })   
    }else {
      updateReceiptOperation.updateReceipt(this, this.options.receiptSid,params) 
        .then(res => {
          that.back()
        }) 
    }
                      
  },

  /**
  * 设置按钮状态
  */
  setButtonLoading: function (loading) {
    this.setData({
      disabled: loading,
      loading: loading
    })
  },

  back:function() {
    setTimeout(function () {
      wx.navigateBack({

      })
    }, 1500)
  }
})